<?php

if (!defined('__BACKEND__'))
    die("you cannot directly access this page");
/*
 * by SONY K Wibisono
 * e-mail : sony@sonywibisono.com
 */
function check_file_exist($filename){
    global $db;
    $sql="select count(*) as cnt from _media_file where filename='$filename'";
    $row=$db->fetch_row($sql);
    if (!empty($row)){
        return $row[0]>0;
    } else return FALSE;
}
function insert_file ($filename,$type){
    global $db;
    $sql="insert into _media_file values (null,'$filename','$type')";
    $db->query($sql);
}
function delete_file_indb ($filename){
    global $db;
    $sql="delete from _media_file where filename='$filename'";
    $db->query($sql);
}
function _recycle(){
    global $db,$DROPBOX_DIR;
    $sql="select * from _media_file";
    $result=$db->query($sql);
    $lastdir="video";
    while ($rwo=$db->fetch_array($result)){
        extract($rwo);
        if ($filetype!='folder'){
            $lastdir=$filename;
            $ext=explode(".",$filename);
            $path=$DROPBOX_DIR."/".$ext[1]."/$filename";
        if (!file_exists($path)){
            //unlink($path);
            delete_file_indb($filename);
        }
            
        }
        
    }
}
function _default_dropbox(){
global $DROPBOX_DIR;
$dir = $DROPBOX_DIR;
_recycle();
// Open a known directory, and proceed to read its contents
?>
<div align="center">
    <h2>MEDIA CONTENTS</h2>
    
    <p align="left">
        <b>Penjelasan!</b>
        <br/>Media Folder adalah folder yang berisi file-file yang mendukung event dan lain-lain kegiatan.</p>
<?php
global $login_status,$is_admin;
echo "Directory : ".$dir;
if (isset($is_admin)&&$is_admin==1){
  echo  "<p align=\"left\">
      <a href=\"?mod=panel\"><img class=\"icon\" 
      src=\"images/panel/admin.png\" title=\"Control Panel\"/></a>
      </p>";
}

?>
    
<table width="100%" cellspacing="0">
    <th align="center"><input id="checkAll" type="checkbox" name="checkAll" value="1"/></th>
    <th>Nama File</th><th>Tipe</th><th>Action</th></tr>
<?php
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $i=0;
        while (($file = readdir($dh)) !== false) {
           if ($file != "." && $file != "..") {
            $filetype=strstr( $file,'.');
            $filetype=str_replace(".", '', $filetype);
            $i++;
            
               echo "<tr><td align=center><img class=icon src=\"images/ic_folder.png\"/></td><td>
            <a href=\"?mod=panel&file=media&action=browse&folder=$file\">$file</a></td><td>Folder</td>
               <td align=\"center\"> </td>
            </tr>\n";
            
            if (!check_file_exist($file)){
                insert_file($file, $filetype);
            }
            
            }
        }
        closedir($dh);
    }
}

?>
</table>
 
<script>
    $("#checkAll").click(function (){
        var a=$("#checkAll").attr('checked');
        if (a){
            $("[rel='docfile']").attr('checked',true);
        } else {
            $("[rel='docfile']").removeAttr('checked');
        }
            
        
    });
    
</script>
</div>
<?php
}
function show_files($folder){
    global $DROPBOX_DIR,$folder;
    $dir=$DROPBOX_DIR."/$folder";
    _recycle();
    if (isset($folder)){
    echo "<p><a href=\"?mod=panel&file=media&action=upload&folder=$folder\"><img class=\"icon\" 
      src=\"images/ic_upload_media.png\" title=\"Upload Media\"/></a></p>";
}
    if (is_dir($dir)) {
        echo "
<a href=\"?mod=panel&file=media\"><img class=icon src=\"images/ic_folder.png\"/>Root Folder</a>   

<table width=\"100%\" cellspacing=\"0\">
    <th align=\"center\"><input id=\"checkAll\" type=\"checkbox\" name=\"checkAll\" value=\"1\"/></th>
    <th>Nama File</th><th>Tipe</th><th>Action</th></tr>";
    if ($dh = opendir($dir)) {
        $i=0;
        while (($file = readdir($dh)) !== false) {
           if ($file != "." && $file != "..") {
            $filetype=strstr( $file,'.');
            $filetype=str_replace(".", '', $filetype);
            $i++;
            
               echo "<tr><td align=center><input rel='docfile' type=\"checkbox\" name=\"doc_file[]\" value=\"$file\"></td><td>
            $file</td><td>$filetype</td>
               <td align=\"center\"> <a href=\"?mod=panel&file=media&filename=$file&action=delete\">
            <img class=icon src=\"images/delete.png\" title=\"Hapus File\"/></a></td>
            </tr>\n";
            
            if (!check_file_exist($file)){
                insert_file($file, $filetype);
            }
            
            }
        }
        closedir($dh);
    }
    echo "</table>";
}
}
function next_step1(){
    global $doc_file,$user_id;
    $media_file=  implode(",", $doc_file);
    echo "<form action=\"?mod=panel&file=media\" method=\"post\">    
    <input type=\"hidden\" name=\"action\" value=\"add_contents\"/>
    <input type=\"hidden\" name=\"media_file\" value=\"$media_file\"/>
<table cellpadding=\"4\" cellspacing=\"0\">
<tr><td colspan='2'><h2>Add Channel Content</h2></td><td> </td></tr>
<tr><td>Channel</td><td>".  select_channel_list(0)." </td></tr>
<tr><td>Title</td><td><input type=\"text\" name=\"title\" class=\"textbox\"/> </td></tr>
<tr><td>Media Embed</td><td><textarea name=\"media_embed\" class=\"textbox\"></textarea> </td></tr>
<tr><td>Media File</td><td>$media_file </td></tr>
<tr><td>Description</td><td><textarea name=\"description\" class=\"textbox\"></textarea> </td></tr>
<tr><td>Hits</td><td><input type=\"text\" name=\"hits\" class=\"textbox\"/> </td></tr>
<tr><td>Hit Like</td><td><input type=\"text\" name=\"hit_like\" class=\"textbox\"/> </td></tr>
<tr><td>Hit Dislike</td><td><input type=\"text\" name=\"hit_dislike\" class=\"textbox\"/> </td></tr>
<tr><td></td><td><input type=\"submit\" value=\"Kirim\"/>
        <input type=\"button\" name=\"cancel\" 
        value=\"Cancel\" onclick=\"javascript:history.go(-1);\"/></td></tr></table></form>";
        
}
function add_process(){
    global $db,$id,$channel_id,$title,$media_embed,$media_file,$description,
            $hits,$hit_like,$hit_dislike,$user_id;
    if (!empty($title)){
        $sql="insert into _channel_contents values (null,$channel_id,'$title',
        '$media_embed','$media_file',
        '$description',0,0,0,sysdate(),$user_id)";
        $db->query($sql);
        refresh_to("?mod=panel&file=channel", "Kembali ke daftar Channel", 1);
    }
}
function upload(){
    global $folder;
    $arfolder= array ('doc','docx','pdf','ppt','pptx');
    if (empty($folder)){
        $folder_list='<select name=\"folder\">\r\n';
        for ($i=0;$i<count($arfolder);$i++){
            $folder_list.="<option value=\"{$arfolder[$i]}\">{$arfolder[$i]}</option>";
        }
        $folder_list.="</select>";
    } else {
        $folder_list="<input type=\"hidden\" name=\"folder\" value=\"$folder\"/>";
    }
    echo "
<img id=\"loading\" src=\"images/ajax-loader.gif\" style=\"display:none;\">        
<form action=\"?mod=panel&file=media\" method=\"post\" enctype=\"multipart/form-data\">
<input type='hidden' name='action' value='upload_process' />
       <table cellpadding=\"0\" cellspacing=\"0\" class=\"tableForm\">

		<thead>
			<tr>
				<th>Please select a file and click Upload button</th>
			</tr>
		</thead>
		<tbody>	
                <tr><td>Folder : $folder_list</td></tr>
			<tr>
				<td><input id=\"fileToUpload\" type=\"file\" 
                                size=\"55\" name=\"fileToUpload\" class=\"textbox\"></td>	
                                </tr>

		</tbody>
			<tfoot>
				<tr>
					<td>
                                        <input type=\"submit\" class=\"button\" 
                                        id=\"buttonUpload\" value=\"Upload\"/>
        <input type=\"button\" onclick=\"javascript:history.go(-1);\" value=\"Cancel\"/></td>
				</tr>
			</tfoot>
	
	</table> 

</form>";
}
function upload_process(){
    global $DROPBOX_DIR,$folder;
    echo "Upload: " . $_FILES["fileToUpload"]["name"] . "<br />";
    echo "Type: " . $_FILES["fileToUpload"]["type"] . "<br />";
    echo "Size: " . ($_FILES["fileToUpload"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["fileToUpload"]["tmp_name"] . "<br />";
    if (file_exists("media/$folder/" . $_FILES["fileToUpload"]["name"]))
      {
      $msg= $_FILES["fileToUpload"]["name"] . " already exists. ";
      //refresh_to("?mod=panel&file=media", $msg, 2);
      }
    else
      {
      move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
      "media/$folder/" . $_FILES["fileToUpload"]["name"]);
      echo "Stored in: " . "media/$folder/" . $_FILES["fileToUpload"]["name"];
      //refresh_to("?mod=panel&file=media", "Upload File sukses, kembali ke daftar media",2);
      }
      
}
function delete_file(){
   global $filename;
   unlink("media/".$filename);
   refresh_to("?mod=panel&file=media", "Back Media List", 1);
}
global $action;

switch($action){
    case 'add_contents':
        add_process();
        break;
    case 'nextstep1':
        next_step1();
        break;
    case 'upload':
        upload();
        break;
    case 'upload_process':
        upload_process();
        break;
    case 'delete':
        delete_file();
        break;
    case 'browse':
        global $folder;
        show_files($folder);
        break;
    default :
        _default_dropbox();
}
?>
<script>
    $("#buttonUpload").click(function(){
        $("#loading").show();
    });
    
</script>
<p align="center">
<a href="?mod=panel&file=media&folder=<?php echo $folder;?>"><img src="images/back_button.png"/></a></p>